/*
 * @Author: AskMeWhy
 * @Date: 2020-12-01 18:05:43
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-02-02 15:58:48
 */

import Vue from "vue";
import Component from "vue-class-component";
import { getRouterConfig } from "@/router";
import { merge, formatList2Level } from "@/utils";
// You can declare mixins as the same style as components.
@Component
export default class FormMixinBase extends Vue {
    getRouterConfig(name: any) {
        return getRouterConfig(name);
    }

    formatUploadData(value: string, type = "array") {
        let res = [];
        const resourceHost = this.$staticUrl;
        if (value) {
            if (typeof value === "string") {
                res = this.formatTextToArray(value).map((cur: any) => {
                    return {
                        url: resourceHost + cur,
                        status: "success"
                    };
                });
            } else {
                const _value = Array.isArray(value) ? value : [value];
                res = _value
                    .filter(
                        (cur: any) => !cur.status || cur.status === "success"
                    )
                    .map((cur: any) =>
                        cur.url
                            ? cur.url.replace(/^https?:\/\/(.*?)(:\d+)?\//, "/")
                            : ""
                    );
            }
        }

        return type === "array" ? res : res[0] === undefined ? {} : res[0];
    }

    formatTextToArray(value: any, sep = ",") {
        if (!value) return [];
        const isArray = Array.isArray(value);
        if (isArray) return value;
        if (typeof value === "string") {
            const _v = value.replace(/\[|\]|\s/g, "");
            return _v ? _v.split(sep) : [];
        }
        return [];
    }

    findIdRelation(
        ids: any[],
        _sourceList: any[],
        key?: string,
        _returnKey?: string
    ) {
        const _key = key || "value";
        let currentValue: any = [];
        const sourceList: any = _sourceList;
        const sourceKey = _key;
        const returnKey = _returnKey || _key;
        if (!Array.isArray(ids)) {
            return currentValue;
        }
        ids = ids.map((cur: any) => {
            return isNaN(Number(cur)) ? cur : Number(cur);
        });
        function hasChildHandler(list: any) {
            const res: any = [];
            for (let i = 0; i < list.length; i++) {
                const cur: any = list[i];
                if (cur.children && cur.children.length > 0) {
                    const _res: any = hasChildHandler(cur.children);
                    _res.forEach((subRes: any) => {
                        res.push([cur[returnKey], ...subRes]);
                    });
                } else {
                    res.push([cur[returnKey]]);
                }
            }
            return res;
        }
        function traverseSourceList(nodes: any) {
            const res = [];
            for (let i = 0; i < nodes.length; i++) {
                const cur = nodes[i];
                const _keyValue = isNaN(Number(cur[sourceKey]))
                    ? cur[sourceKey]
                    : Number(cur[sourceKey]);
                if (ids.includes(_keyValue)) {
                    if (cur.children && cur.children.length > 0) {
                        const _res = hasChildHandler(cur.children);
                        _res.forEach((subRes: any) => {
                            res.push([
                                returnKey === "_obj_" ? cur : cur[returnKey],
                                ...subRes
                            ]);
                        });
                    } else {
                        res.push([
                            returnKey === "_obj_" ? cur : cur[returnKey]
                        ]);
                    }
                } else {
                    if (cur.children && cur.children.length > 0) {
                        const _res = traverseSourceList(cur.children);
                        _res.forEach((subRes: any) => {
                            res.push([
                                returnKey === "_obj_" ? cur : cur[returnKey],
                                ...subRes
                            ]);
                        });
                    }
                }
            }
            return res;
        }
        currentValue = traverseSourceList(sourceList);
        return currentValue;
    }

    buildTypeList(list: any[], formatList?: any, opt?: any) {
        const option = merge(
            true,
            {
                    label: "name",
                    value: "id",
                    children: "children",
                    callback: null
            },
            opt || {}
        );
        let _list = this.formateTypeList(list, option);
        const _formatList = formatList || false;
        if (_formatList) {
            const isObj =
                Object.prototype.toString.call(_formatList) ===
                "[object Object]";
            let defaultOption = { level: 2 };
            if (isObj) {
                defaultOption = { ...defaultOption, ..._formatList };
            }
            _list = formatList2Level(_list, defaultOption.level);
        }
        return _list;
    }

    formateTypeList(list: any[], option?: any) {
        const opt = merge(
            true,
            {
                label: "name",
                value: "id",
                children: "children",
                callback: null
            },
            option || {}
        );
        let res: any[] = [];
        res = list.map(item => {
            let cur: any = {};
            if (opt.callback) {
                cur = opt.callback(item, opt);
            } else {
                cur.label = item[opt.label];
                cur.value = item[opt.value];
                cur.source = item;
            }
            if (item[opt.children] && item[opt.children].length > 0) {
                cur.children = this.formateTypeList(
                    item[opt.children],
                    opt
                );
            }
            return cur;
        });
        return res;
    }

    responseHasError(res: any, callback?: any) {
        if (
            (!res.data && !res.response) ||
            (res.response && res.response.status !== 200) ||
            res.data.code !== 200
        ) {
            if (callback) {
                callback(res);
            } else {
                this.$message.error(
                    (res.data ? res.data.message : res.message) ||
                        "接口请求错误!"
                );
            }
            return true;
        }
        return false;
    }
}
